var emptyHtml = '<option value="">全部</option>';
var emptyCityHtml = '<option value="">城市</option>';
var emptyDistrictHtml = '<option value="">区县</option>';
$(document).ready(function() {
	layui.use('form', function(){
		//表单
		_form = layui.form;
		
		//省份选择
		_form.on('select(provinceId)', function(data){
			provinceChange('provinceId','cityId','districtId');
	    });  
		
		_form.on('select(cProvinceId)', function(data){
			provinceChange('cProvinceId','cCityId','cDistrictId');
	    });  
		
		_form.on('select(mProvinceId)', function(data){
			provinceChange('mProvinceId','mCityId','mDistrictId');
	    });
		
		//城市选择
		/*_form.on('select(cityId)', function(data){
			cityChange('cityId','districtId');
	    });
		
		_form.on('select(cCityId)', function(data){
			cityChange('cCityId','cDistrictId');
	    });
		
		_form.on('select(mCityId)', function(data){
			cityChange('mCityId','mDistrictId');
	    });*/
	});
});

/**
 * 选择省份
 * 
 * @param provinceId:省份Id
 * @param cityId:控件Id
 * @param districtId:控件Id
 */
function provinceChange(provinceId, cityId, districtId) {
	var $provinceId = $.trim($("#" + provinceId + " option:selected").val());
	if ($provinceId == "") {
		$("#" + cityId).html(emptyCityHtml);
	}
	else {
		// 加载城市
		$("#" + cityId).html(queryCityByProvince($provinceId));
	}

	if (typeof (districtId) == "undefined" || districtId == null) {
	}
	else {
		$("#" + districtId).html(emptyDistrictHtml);
	}
	
	updateLayuiForm();
}

/**
 * 选择城市
 * 
 * @param cityId:城市Id
 * @param districtId:控件Id
 */
function cityChange(cityId, districtId) {
	var $cityId = $.trim($("#" + cityId + " option:selected").val());
	if ($cityId == "") {
		$("#" + districtId).html(emptyDistrictHtml);
	}
	else {
		// 加载城市
		$("#" + districtId).html(queryDistrictByCity($cityId));
	}
	
	updateLayuiForm();
}

/**
 * 获取城市
 */
function queryCityByProvince($provinceId) {
	// 初始化
	var opts = "";

	// 调用接口
	var response = callInterface("post", "home/queryCity", {
		"provinceId" : $provinceId
	}, false);
	if (response.code == 0) {
		if (response.data != null) {
			opts += emptyCityHtml;
			$(response.data).each(function(i, temp) {
				opts += '<option value="' + temp.id + '">' + temp.name + '</option>';
			});
		}
	}
	else {
		showErrorMsg(response.code, response.message);
	}

	// 返回数据
	return opts;
}

/**
 * 获取区县
 */
function queryDistrictByCity($cityId) {
	// 初始化
	var opts = "";

	// 调用接口
	var response = callInterface("post", "home/queryDistrict", {
		"cityId" : $cityId
	}, false);
	
	if (response.code == 0) {
		if (response.data != null) {
			opts += emptyDistrictHtml;
			$(response.data).each(function(i, temp) {
				opts += '<option value="' + temp.id + '">' + temp.name + '</option>';
			});
		}
	}
	else {
		showErrorMsg(response.code, response.message);
	}

	// 返回数据
	return opts;
}